package main

import (
	"context"
	"crypto/tls"
	"crypto/x509"
	"flag"
	"io/ioutil"
	"log"
	"os"
	"time"

	"gitee.com/jason_elva8325/sd-etcd-v3"
	"gitee.com/jason_elva8325/sd-etcd-v3/examples/pb"
	"google.golang.org/grpc"
	"google.golang.org/grpc/balancer/roundrobin"
	"google.golang.org/grpc/resolver"
)

var svcName = "project/test"
var etcdAddr = "127.0.0.1:2379"
var testlog = log.New(os.Stderr, "[example.client] ", log.LstdFlags|log.Lmicroseconds|log.Lshortfile)

func main() {
	flag.StringVar(&svcName, "svcName", svcName, "svcName")
	flag.StringVar(&etcdAddr, "etcdAddr", etcdAddr, "etcdAddr to reg")
	flag.Parse()
	// load cert
	cert, err := tls.LoadX509KeyPair("/tmp/client.pem", "/tmp/client-key.pem")
	if err != nil {
		panic(err)
	}

	// load root ca
	caData, err := ioutil.ReadFile("/tmp/ca.pem")
	if err != nil {
		panic(err)
	}

	pool := x509.NewCertPool()
	pool.AppendCertsFromPEM(caData)

	sd.SetScheme("testsvc")
	r := sd.NewResolver(etcdAddr, &tls.Config{
		Certificates: []tls.Certificate{cert},
		RootCAs:      pool,
	})
	resolver.Register(r)

	conn, err := grpc.Dial(r.Scheme()+":///"+svcName, grpc.WithBalancerName(roundrobin.Name), grpc.WithInsecure())
	if err != nil {
		panic(err)
	}

	ticker := time.NewTicker(2 * time.Second)
	for range ticker.C {
		client := pb.NewHelloServiceClient(conn)
		// set rpc call timeout
		ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
		defer cancel()
		resp, err := client.Echo(ctx, &pb.Payload{Data: "hello"}, grpc.FailFast(true))
		if err != nil {
			testlog.Printf("grpc call fail: %v", err.Error())
		} else {
			testlog.Println(resp)
		}
	}
}
